import React, { useState, useEffect, useCallback } from 'react';
import {
    View,
    Text,
    Modal,
    TouchableOpacity,
    StyleSheet,
    Animated,
    Easing,
    SafeAreaView,
} from 'react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';

/**
 * 按钮配置对象
 * @typedef {Object} ButtonConfig
 * @property {string} text - 按钮文本
 * @property {string} [icon] - FontAwesome图标名称
 * @property {string} [color] - 按钮背景颜色
 * @property {('left'|'right')} [iconPosition] - 图标位置
 * @property {function} onPress - 点击事件处理函数
 * @property {boolean} [autoClose=true] - 点击后是否自动关闭弹窗
 */

/**
 * 按钮弹窗组件
 * @param {Object} props
 * @param {boolean} props.visible - 控制弹窗显示/隐藏
 * @param {function} props.onClose - 关闭弹窗的回调函数
 * @param {string} [props.title] - 弹窗标题
 * @param {string} [props.content] - 弹窗内容文本
 * @param {ButtonConfig[]} [props.buttons] - 按钮配置数组
 * @param {('scale'|'slide'|'fade')} [props.animationType='scale'] - 动画类型
 * @param {object} [props.containerStyle] - 容器自定义样式
 * @param {object} [props.titleStyle] - 标题自定义样式
 * @param {object} [props.contentStyle] - 内容自定义样式
 * @param {object} [props.buttonContainerStyle] - 按钮容器自定义样式
 * @param {string} [props.backdropColor='rgba(0, 0, 0, 0.5)'] - 背景遮罩颜色
 */
const ButtonModal = ({
    visible,
    onClose,
    title,
    content,
    buttons = [{ text: '关闭', onPress: onClose }],
    animationType = 'scale',
    containerStyle,
    titleStyle,
    contentStyle,
    buttonContainerStyle,
    backdropColor = 'rgba(0, 0, 0, 0.5)',
}) => {
    const [animation] = useState(new Animated.Value(0));
    const [modalVisible, setModalVisible] = useState(false);
    const [renderContent, setRenderContent] = useState(false);

    // 使用 useCallback 缓存 animateModal 函数
    const animateModal = useCallback((isOpening) => {
        if (isOpening) {
            // 重置动画值
            animation.setValue(0);

            // 同时设置内容渲染和 Modal 可见性，避免闪烁
            setRenderContent(true);
            setModalVisible(true);

            // 立即开始动画，无需延迟
            const config = {
                toValue: 1,
                duration: 300,
                useNativeDriver: false,
            };

            let animProps = {};
            if (animationType === 'scale') {
                animProps = {
                    ...config,
                    easing: Easing.out(Easing.back(0.3)),
                };
            } else if (animationType === 'slide') {
                animProps = {
                    ...config,
                    easing: Easing.out(Easing.cubic),
                };
            } else {
                animProps = {
                    ...config,
                    easing: Easing.linear,
                };
            }

            Animated.timing(animation, animProps).start();
        } else {
            // 执行退出动画
            const config = {
                toValue: 0,
                duration: 300,
                useNativeDriver: false,
            };

            let animProps = {};
            if (animationType === 'scale') {
                animProps = {
                    ...config,
                    easing: Easing.in(Easing.back(0.3)),
                };
            } else if (animationType === 'slide') {
                animProps = {
                    ...config,
                    easing: Easing.in(Easing.cubic),
                };
            } else {
                animProps = {
                    ...config,
                    easing: Easing.linear,
                };
            }

            Animated.timing(animation, animProps).start(() => {
                // 动画结束后隐藏内容和 Modal
                setModalVisible(false);
                setRenderContent(false);
            });
        }
    }, [animation, animationType]);

    useEffect(() => {
        if (visible) {
            animateModal(true);
        } else {
            animateModal(false);
        }
    }, [visible, animateModal]);

    const getAnimationStyles = () => {
        if (animationType === 'scale') {
            const scale = animation.interpolate({
                inputRange: [0, 1],
                outputRange: [0.8, 1],
            });
            return { transform: [{ scale }] };
        } else if (animationType === 'slide') {
            const translateY = animation.interpolate({
                inputRange: [0, 1],
                outputRange: [50, 0],
            });
            return { transform: [{ translateY }] };
        }
        return { opacity: animation };
    };

    const handleClose = () => {
        animateModal(false);
        if (onClose) onClose();
    };

    return (
        <Modal
            visible={modalVisible}
            transparent={true}
            animationType="none"
            onRequestClose={handleClose}
        >
            <SafeAreaView style={[styles.overlay, { backgroundColor: backdropColor }]}>
                <View style={styles.overlay}>
                    {renderContent && (
                        <Animated.View
                            style={[
                                styles.modalContainer,
                                getAnimationStyles(),
                                containerStyle,
                            ]}
                        >
                            {title && (
                                <View style={styles.titleContainer}>
                                    <Text style={[styles.title, titleStyle]}>{title}</Text>
                                </View>
                            )}

                            {content && (
                                <Text style={[styles.content, contentStyle]}>{content}</Text>
                            )}

                            <View style={[styles.buttonContainer, buttonContainerStyle]}>
                                {buttons.map((button, index) => (
                                    <TouchableOpacity
                                        key={index}
                                        style={[
                                            styles.button,
                                            { backgroundColor: button.color || '#2196F3' },
                                        ]}
                                        onPress={() => {
                                            button.onPress();
                                            if (button.autoClose !== false) {
                                                handleClose();
                                            }
                                        }}
                                    >
                                        {button.icon && button.iconPosition !== 'right' && (
                                            <FontAwesome
                                                name={button.icon}
                                                size={18}
                                                color="white"
                                                style={styles.buttonIcon}
                                            />
                                        )}

                                        <Text style={styles.buttonText}>{button.text}</Text>

                                        {button.icon && button.iconPosition === 'right' && (
                                            <FontAwesome
                                                name={button.icon}
                                                size={18}
                                                color="white"
                                                style={styles.buttonIconRight}
                                            />
                                        )}
                                    </TouchableOpacity>
                                ))}
                            </View>
                        </Animated.View>
                    )}
                </View>
            </SafeAreaView>
        </Modal>
    );
};

const styles = StyleSheet.create({
    overlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContainer: {
        backgroundColor: 'white',
        borderRadius: 10,
        padding: 20,
        width: '80%',
        maxWidth: 350,
        elevation: 8,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        // 改用 Flex 布局居中
        alignSelf: 'center',
        // 使用数值而不是百分比，确保稳定性
        transform: [{ translateY: -150 }],
    },
    titleContainer: {
        marginBottom: 15,
    },
    title: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        textAlign: 'center',
    },
    content: {
        fontSize: 16,
        color: '#666',
        marginBottom: 20,
        textAlign: 'center',
    },
    buttonContainer: {
        flexDirection: 'column',
        gap: 10,
    },
    button: {
        borderRadius: 5,
        padding: 12,
        elevation: 2,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    buttonText: {
        color: 'white',
        fontWeight: 'bold',
        fontSize: 16,
    },
    buttonIcon: {
        marginRight: 8,
    },
    buttonIconRight: {
        marginLeft: 8,
    },
});

export default ButtonModal;
